package com.holystone.orca.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.holystone.orca.common.JSONMapper;
import com.holystone.orca.common.PageData;
import com.holystone.orca.sys.common.SystemConstant;
import com.holystone.orca.sys.mybatis.model.SysCompany;
import com.holystone.orca.sys.mybatis.model.SysDepartment;
import com.holystone.orca.sys.service.ISysCompanyService;
import com.holystone.orca.sys.service.ISysDepartmentService;
 
@Controller
@RequestMapping("/sys/dep_management")
public class SysDepController {

	private static Logger logger = Logger.getLogger(SysDepController.class);
	
	private static String LOGIN_KEY = "loginKey";
	
	private String baseUrl = "sys/dep_management/";
	
	@Resource(name="sysDepartmentService")
	private ISysDepartmentService sysDepService;
	@Resource(name="sysCompanyService")
	private ISysCompanyService sysCompanyService;
	
    @RequestMapping("/menuDepList")
    public ModelAndView initPersonList(){
    	ModelAndView model = new ModelAndView(baseUrl+"dep_management");
        return model;
    }
    
    //分页，初始化页面
    @ResponseBody
    @RequestMapping("/pagingDepList")
    public ModelMap pagingDepList(String  iPageNo, String iPageSize,String depName,ModelMap modelMap){
    	int pageindex = iPageNo!=null?Integer.parseInt(iPageNo):SystemConstant.default_pageNum;
        int pagesize = iPageSize!=null?Integer.parseInt(iPageSize):SystemConstant.default_pageSize;
        PageData pageData = new PageData();
        List<SysCompany> list=sysCompanyService.selectCompany();
        try{
        	pageData = sysDepService.pagingSysDep(pageindex, pagesize, "depName", depName);
        }catch(Exception e){
            logger.error(e,e);
        }
        modelMap=JSONMapper.createReturnMap(null, pageData, null);
        modelMap.put("companyList", list);
        return modelMap;
    }
    
    //初始化子部门页面
    @RequestMapping("/initDepChild")
    public ModelAndView initChildList(int depId,ModelMap modelMap,String depName){
    	modelMap.put("depId", depId);
    	modelMap.put("depName", depName);
    	ModelAndView model = new ModelAndView(baseUrl+"dep_child_management");
        return model;
    }
    
    //分页，初始化子部门
    @ResponseBody
    @RequestMapping("/pagingDepChildList")
    public ModelMap pagingDepChildList(String  iPageNo, String iPageSize,String depName,String depId,ModelMap modelMap){
    	int pageindex = iPageNo!=null?Integer.parseInt(iPageNo):SystemConstant.default_pageNum;
        int pagesize = iPageSize!=null?Integer.parseInt(iPageSize):SystemConstant.default_pageSize;
        PageData pageData = new PageData();
        List<SysCompany> list=sysCompanyService.selectCompany();
        try{
        	pageData = sysDepService.pagingSysChildDep(pageindex, pagesize, "depId", depName,depId);
        }catch(Exception e){
            logger.error(e,e);
        }
        modelMap=JSONMapper.createReturnMap(null, pageData, null);
        modelMap.put("companyList", list);
        return modelMap;
    } 
    
    
    
    //添加，修改部门页面
    @RequestMapping(value="/initEditSysDep")
	public ModelAndView initEditSysDep(String depId,String opera){
		logger.debug(">>>initEditSysDep(String "+depId+",String "+opera+")添加，修改部门页面");
		ModelAndView view = new ModelAndView(baseUrl+"add_dep");
		List<SysCompany> list=new ArrayList<SysCompany>();
		List<SysDepartment> depList=new ArrayList<SysDepartment>();
		Map<Object,String> map=new HashMap<Object,String>();
		if(opera!=null&&opera.equals("add")){//添加
			try {
				list=sysCompanyService.selectCompany();
				depList=sysDepService.selectParentDep(map);
			} catch (Exception e) {
				logger.error(e,e);
			}
			view.addObject("sysCompanyList", list);
			view.addObject("parentDepList",depList);
		}else if(opera!=null&&opera.equals("edit")){//修改
			SysDepartment sysDepartment=new SysDepartment();
			Map<Object,String> depMap = new HashMap<Object,String>();
			depMap.put("depId", depId);
			try {
				list=sysCompanyService.selectCompany();
				depList=sysDepService.selectDepNoSelfBydepId(depMap);
				sysDepartment=sysDepService.selectDepBydepId(Integer.parseInt(depId));
			} catch (Exception e) {
				logger.error(e,e);
			}
			view.addObject("depId", depId);
			view.addObject("Dep", sysDepartment);
			view.addObject("sysCompanyList", list);
			view.addObject("parentDepList",depList);
		}
		logger.debug("<<<initEditSysRole(depId "+depId+")");
		return view;
	}
    
    //点击添加请求
    @ResponseBody
    @RequestMapping("/addSysDep")
    public ModelMap addSysDep(SysDepartment sysDepartment,String cmpName,String parName){
    	logger.debug("<<<addSysDep(SysDepartment "+sysDepartment+",cmpName "+cmpName+",parName "+parName+")<<<添加部门信息");
    	boolean flag=false;
    	Map<Object,String> map=new HashMap<Object,String>();
    	Map<Object,String> map1=new HashMap<Object,String>();
		map1.put("depName", sysDepartment.getDepName());
		map1.put("cmpName", cmpName);
    	if(parName.equals("无")){
    		try {
				List<SysDepartment> sysDepartmentList = sysDepService.selectIsHaveDep(map1);
				if(sysDepartmentList.size() != 0){
					return JSONMapper.createReturnMap("部门名重复！", null, flag);
				}
			} catch (Exception e) {
				logger.error(e,e);
			}
    		//如果选择部门为父级部门，则depPid为0
    		map.put("depPid", "0");
    	}else{
    		
    		String depId="";
			try {
				//如果不为父级部门，查找父级部门的depId
				List<SysDepartment> sysDepartmentList = sysDepService.selectIsHaveDep(map1);
				if(sysDepartmentList.size() != 0){
					return JSONMapper.createReturnMap("部门名重复！", null, flag);
				}else{
					Map<Object,String> map2=new HashMap<Object,String>();
					map2.put("depName", parName);
					map2.put("cmpName", cmpName);
					List<SysDepartment> sysDepList = sysDepService.selectIsHaveDep(map2);
					depId = sysDepList.get(0).getDepId()+"";
				}
			} catch (Exception e) {
				logger.error(e,e);
			}
    		map.put("depPid", depId);
    	}
    	map.put("cmpName", cmpName);
    	map.put("depName", sysDepartment.getDepName());
    	map.put("state", sysDepartment.getState());
    	map.put("remark", sysDepartment.getRemark());
    	try {
    		//添加数据到map，添加部门
			flag=sysDepService.addDep(map);
		} catch (Exception e) {
			 logger.error(e,e);
		}
    	return JSONMapper.createReturnMap("修改成功", null, flag);
    } 
    
  //编辑部门信息
    @ResponseBody
    @RequestMapping("/editSysDep")
    public ModelMap editSysDep(SysDepartment sysDepartment,String cmpName,String parName){
    	boolean flag=false;
    	Map<String,String> map=new HashMap<String,String>();
    	Map<Object,String> map1=new HashMap<Object,String>();
		map1.put("depName", sysDepartment.getDepName());
		map1.put("cmpName", cmpName);
    	if(parName.equals("无")){
    		try {
				List<SysDepartment> sysDepartmentList = sysDepService.selectIsHaveDep(map1);
				SysDepartment sysDep = sysDepService.selectDepBydepId(sysDepartment.getDepId());
				if(sysDepartmentList.size() != 0 && !(sysDep.getDepName().equals(sysDepartment.getDepName()))){ 
					return JSONMapper.createReturnMap("部门名重复！", null, flag);
				}
			} catch (Exception e) {
				logger.error(e,e);
			}
    		map.put("depPid", "0");
    	}else{
    		
    		String depPid="";
			try {
				List<SysDepartment> sysDepartmentList = sysDepService.selectIsHaveDep(map1);
				List<SysDepartment> sysDep = sysDepService.selectDepartById(sysDepartment.getDepId());
				if(sysDepartmentList.size() != 0 && !(sysDep.get(0).getDepName().equals(sysDepartment.getDepName()))){
					return JSONMapper.createReturnMap("部门名重复！", null, flag);
				}else{
					Map<Object,String> map2=new HashMap<Object,String>();
					map2.put("depName", parName);
					map2.put("cmpName", cmpName);
					List<SysDepartment> sysDepList = sysDepService.selectIsHaveDep(map2);
					depPid = sysDepList.get(0).getDepId()+"";
				}
			} catch (Exception e) {
				logger.error(e,e);
			}
    		map.put("depPid", depPid);
    	}
    	map.put("cmpName", cmpName);
    	map.put("depName", sysDepartment.getDepName());
    	map.put("state", sysDepartment.getState());
    	map.put("remark", sysDepartment.getRemark());
    	map.put("depId",sysDepartment.getDepId()+"");
    	try {
			flag=sysDepService.editDepBydepId(map);
		} catch (Exception e) {
			logger.error(e,e);
		}
    	return JSONMapper.createReturnMap("修改成功", null, flag);
    }
    
    //删除点击的部门
    @ResponseBody
    @RequestMapping("/deleteDepByDepId")
    public ModelMap deleteDepByDepId(int depId){
    	boolean flag=false;
    	try {
    		flag=sysDepService.delDepByDepId(depId);
    	} catch (Exception e) {
    		logger.error(e,e);
    	}
    	return JSONMapper.createReturnMap(null, null, flag);
    }

    //多项删除
    @ResponseBody
    @RequestMapping("/deleteSelectSysDep")
    public ModelMap deleteSelectSysDep(String checkedDel){
    	boolean flag=false;
    	checkedDel=checkedDel.substring(0, checkedDel.length() - 1);
    	String[] arry=null;
    	arry=checkedDel.split(",");
    	List<Integer> list=new ArrayList<Integer>();
    	for(int i=0;i<arry.length;i++){
    		list.add(Integer.parseInt(arry[i]));
    	}
    	try {
    		flag=sysDepService.delSelectDep(list);
    	} catch (Exception e) {
    		logger.error(e,e);
    	}
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    
    @ResponseBody
    @RequestMapping("/selectDepBycmpId")
    public ModelMap selectDepBycmpId(ModelMap modelMap,Integer cmpId){
    	Map<Object,String> map = new HashMap<Object,String>();
    	map.put("cmpId", cmpId+"");
    	List<SysDepartment> depList=new ArrayList<SysDepartment>();
    	try {
			depList=sysDepService.selectParentDep(map);
		} catch (Exception e) {
			logger.error(e,e);
		}
    	return JSONMapper.createReturnMap(null, null, depList);
    }
    
    @ResponseBody
    @RequestMapping("/selectEditDepBycmpId")
    public ModelMap selectEditDepBycmpId(ModelMap modelMap,Integer cmpId,Integer depId){
    	Map<Object,String> map = new HashMap<Object,String>();
    	map.put("cmpId", cmpId+"");
    	map.put("depId", depId+"");
    	List<SysDepartment> depList=new ArrayList<SysDepartment>();
    	try {
			depList=sysDepService.selectDepNoSelfBydepId(map);
		} catch (Exception e) {
			logger.error(e,e);
		}
    	return JSONMapper.createReturnMap(null, null, depList);
    }
}